package io.file;

import java.io.File;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class NIODemo {

	public static void main(String[] args) throws Exception {

		new File("D:\\testNIOFile.txt").deleteOnExit();

		// 写文件
		ByteBuffer writeBuffer = ByteBuffer.allocate(1024 * 1024);
		writeBuffer.put("hello nio file test ~".getBytes());
		FileChannel writeChannel = FileChannel.open(Paths.get("D:\\testNIOFile.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
		writeBuffer.flip();
		writeChannel.write(writeBuffer);
		writeChannel.close();

		// 读文件
		ByteBuffer readBuffer = ByteBuffer.allocate(1024 * 1024);
		FileChannel readChannel = FileChannel.open(Paths.get("D:\\testNIOFile.txt"), StandardOpenOption.READ);
		while (readChannel.read(readBuffer) != -1) {
			System.out.println(new String(readBuffer.array()));
			readBuffer.rewind();
		}
		readChannel.close();
	}
}